package hn.info.hockeynews.helpers;

import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import hn.info.hockeynews.dao.DaoMaster;
import hn.info.hockeynews.dao.DaoSession;
import hn.info.hockeynews.dao.Entry;
import hn.info.hockeynews.dao.EntryDao;
import hn.info.hockeynews.dao.DaoMaster.DevOpenHelper;
import hn.info.hockeynews.dao.EntryDao.Properties;
import de.greenrobot.dao.QueryBuilder;

public class DBHelperEntries {

	private EntryDao entryDao;
	private DaoMaster daoMaster;
    private DaoSession daoSession;
    private Cursor cursor;
	private SQLiteDatabase db;
	
	/**
	 * check if there is any data in db
	 * */
	public String checkData(long match_id) {
		try {
			QueryBuilder<Entry> qb = entryDao.queryBuilder().where(EntryDao.Properties.Match_id.eq(match_id)).orderDesc(Properties.Entry_id);
			return "notnull";
		}
		catch(Exception e) {
			return "null";
		}
	}
	
	public void insertEntry(Entry e, DevOpenHelper helper) {
		db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        entryDao = daoSession.getEntryDao();
        
        entryDao.insertOrReplace(e);
        
		Log.d("DB", "Added :"+e.getInfo()+"Time: "+e.getTimestamp()+" Data :"+e.toString());
	}
	
	/**
	 * read data from db
	 * */
	public List<Entry> getEntryData(long id, DevOpenHelper helper) {
		daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        entryDao = daoSession.getEntryDao();
		QueryBuilder<Entry> qbl = entryDao.queryBuilder().where(Properties.Match_id.eq(id)).orderAsc(Properties.Entry_time);
		List<Entry> el = qbl.list();
		//closeDB();
		return el;
	}
	
	public void closeDB() {
		db.close();
	}
	
	public void killDB(DevOpenHelper helper) {
		db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        entryDao = daoSession.getEntryDao();
        
        entryDao.deleteAll();
	}
}
